package edu.mapi.ir.viewer;

import java.awt.Shape;
import java.awt.geom.Area;
import java.awt.geom.Ellipse2D;
import java.awt.geom.GeneralPath;
import java.awt.geom.Point2D;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Vector;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

/**
 * @author ZP
 */
public class GridPosition {

	public Point2D position;
	public double direction;
	
	public GridPosition(Point2D position, double direction) {
		this.position = position;
		this.direction = direction;
	}
	
	public static Vector<GridPosition> readStream(InputStream stream) throws Exception {
	Vector<GridPosition> grid = new Vector<GridPosition>();
		
		DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance();
		DocumentBuilder db = fac.newDocumentBuilder();
		Document doc = db.parse(stream);
		
		NodeList posNodes = doc.getElementsByTagName("Position");
		
		for (int i = 0; i < posNodes.getLength(); i++) {			
			String dir = posNodes.item(i).getAttributes().getNamedItem("Dir").getTextContent();
			String x = posNodes.item(i).getAttributes().getNamedItem("X").getTextContent();
			String y = posNodes.item(i).getAttributes().getNamedItem("Y").getTextContent();
			GridPosition position = new GridPosition(new Point2D.Double(Double.parseDouble(x), Double.parseDouble(y)), Double.parseDouble(dir));
			grid.add(position);
		}
		
		return grid;
	}
		
	
	public static Vector<GridPosition> readFile(File f) throws Exception {
		return readStream(new FileInputStream(f));
	}
	
	public static Vector<GridPosition> readString(String xml) throws Exception {
		return readStream(new ByteArrayInputStream(xml.getBytes()));
	}
	
	public Shape getShape() {
		
		Ellipse2D.Double ellis = new Ellipse2D.Double(position.getX()-0.5, position.getY()-0.5, 1, 1);		
		Ellipse2D.Double ellis2 = new Ellipse2D.Double(position.getX()-0.4, position.getY()-0.4, 0.8, 0.8);
		Area area = new Area(ellis);
		
		
		double angRad = Math.toRadians(direction);
		
		GeneralPath path = new GeneralPath();
		path.moveTo(position.getX()+(Math.cos(angRad))/2, 
				position.getY()+(Math.sin(angRad))/2);
		
		path.lineTo(position.getX()+(Math.cos(angRad+Math.toRadians(140))/2), 
				position.getY()+(Math.sin(angRad+Math.toRadians(140)))/2);
		
		path.lineTo(position.getX()+(Math.cos(angRad+Math.toRadians(220))/2), 
				position.getY()+(Math.sin(angRad+Math.toRadians(220)))/2);
		path.closePath();
		
		area.subtract(new Area(ellis2));
		area.add(new Area(path));
		
		return area;
	}
}
